package com.xiaoyg.algorithm;

import java.util.LinkedList;
import java.util.Queue;

public class SymmetricTree {
    public static void main(String[] args) {
        TreeNode root1 = new TreeNode(6);
        TreeNode root3 = new TreeNode(7);
        TreeNode root4 = new TreeNode(7);
        TreeNode root5 = new TreeNode(8);
        TreeNode root6 = new TreeNode(9);
        TreeNode root7 = new TreeNode(9);
        TreeNode root8 = new TreeNode(8);

        root1.left = root3;
        root1.right = root4;
        root3.left = root5;
        root3.right = root6;

        root4.left = root7;
        root4.right = root8;

        System.out.println(isSymmetric(root1));

    }

    public static boolean isSymmetric(TreeNode left, TreeNode right){
        //左子树的左子树 = 右子树的右子树
        //左子树的右子树 = 右子树的左子树
        if (left == null && right == null){
            return true;
        }
        if (left == null || right == null){
            return false;
        }
        if (left.val != right.val){
            return false;
        }
        return isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left);
    }


    public static boolean isSymmetric(TreeNode root){
        //左子树的左子树 = 右子树的右子树
        //左子树的右子树 = 右子树的左子树
        if (root == null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode left = root.left;
        TreeNode right = root.right;
        if (left == null && right == null){
            return true;
        }
        queue.offer(left);
        queue.offer(right);
        while (!queue.isEmpty()){
            left = queue.poll();
            right = queue.poll();

            if (left == null && right == null){
                continue;
            }
            if (left ==null || right == null){
                return false;
            }
            if (left.val!=right.val){
                return false;
            }
            queue.offer(left.left);
            queue.offer(right.right);
            queue.offer(left.right);
            queue.offer(right.left);
        }
        return true;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
